package com.dazzle.cameralib;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.dazzle.cameralib.utils.DebugUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by gavin on 2016/11/21.
 */

class TackPicture implements Camera.PictureCallback{
    public static final String TAG = "TackPicture";

    private String mPictureSaveDir;
    private String mPictureSavePath;
    private OnSavePictureListener mOnSavePictureListener;

    private Context mContext;
    public TackPicture(Context context) {
        mContext = context;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            saveToSDCard(data); // 保存图片到sd卡中
            camera.startPreview(); // 拍完照后，重新开始预览
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 得到图片保存的目录
     *
     * @return
     */
    public String getPictureSaveDir() {
        String path;
        if (mPictureSaveDir == null)
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                path = Environment.getExternalStorageDirectory()
                        + "/SolidCamera/";
            else {
                path = mContext.getCacheDir().getAbsolutePath()
                        + "/SolidCamera/";
            }
        else {
            path = mPictureSaveDir;
        }
        mPictureSaveDir = path;
        return path;
    }


    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    private void saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";

        File fileFolder = new File(getPictureSaveDir());

        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流

        Matrix matrix = new Matrix();

        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        outputStream.flush(); // 写入sd卡中
        outputStream.close(); // 关闭输出流
        mPictureSavePath = getPictureSaveDir() + File.separator + filename;

        if (mOnSavePictureListener != null) {
            mOnSavePictureListener.onSuccess(mPictureSavePath);
        }

        Toast.makeText(mContext.getApplicationContext(), "图片已保存至:" + mPictureSavePath,
                Toast.LENGTH_LONG).show();

        notifyMediaScanner(mPictureSavePath);
    }

    void notifyMediaScanner(String path) {
        //这个的作用是让系统去扫描刚拍下的这个图片文件，以利于在MediaSore中能及时更新，
        MediaScannerConnection.scanFile(mContext, new String[]{mPictureSavePath},
            null, new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    DebugUtils.LogE(TAG, "扫描完成");
                }
                });
    }

    public void setOnSavePictureListener(OnSavePictureListener onSavePictureListener) {
        mOnSavePictureListener = onSavePictureListener;
    }

    public interface OnSavePictureListener {
        void onSuccess(String filePath);
    }
}
